/*******************************************************************************
 * Copyright (c) 2011 EclipseDevX.org and others.
 * 
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at:
 * 
 *     http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

package org.eclipsedevx.appengine.usage;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.channels.Channels;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;

@SuppressWarnings("serial")
public class ViewReportServlet extends HttpServlet {
	
	public ViewReportServlet() {
		
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		FileService fileService = FileServiceFactory.getFileService();
		
		BlobKey blobKey = BlobUtil.getBlobNamed(ReportGenerator.FILE_NAME);
		
		if (blobKey != null) {
			resp.setContentType("text/html");
			
			AppEngineFile file = fileService.getBlobFile(blobKey);
			
			FileReadChannel inChannel = fileService.openReadChannel(file, false);
			
			BufferedReader reader = new BufferedReader(Channels.newReader(inChannel, "UTF8"));
			char[] buffer = new char[4096];
			
			int count = reader.read(buffer);
			
			while (count > 0) {
				resp.getWriter().write(buffer, 0, count);
				count = reader.read(buffer);
			}
			
			reader.close();
			inChannel.close();
			
			resp.getWriter().close();
		} else {
			resp.setContentType("text/plain");
			resp.getWriter().println("[-]");
		}
	}
	
}
